package com.computergames.server.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

@ChannelHandler.Sharable
public class ConnectionTimeHandler extends ChannelInboundHandlerAdapter {
    long totalWaitTime;
    long totalIoTime;
    int totalConnections;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 记录连接开始时间
        long startTime = System.currentTimeMillis();
        ctx.channel().attr(AttributeKey.valueOf("startTime")).set(startTime);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // 记录连接结束时间
        long startTime = (long)ctx.channel().attr(AttributeKey.valueOf("startTime")).get();
        long endTime = System.currentTimeMillis();
        long waitTime = endTime - startTime;
        long ioTime = endTime - startTime; // 假设 IO 时间等于等待时间

        totalWaitTime += waitTime;
        totalIoTime += ioTime;
        totalConnections++;

        System.out.println("Connection: Wait Time = " + waitTime + "ms, IO Time = " + ioTime + "ms");
    }
    public double calculateAverageTimes() {
        if (totalConnections > 0) {
            double avgWaitTime = (double) totalWaitTime / totalConnections;
            double avgIoTime = (double) totalIoTime / totalConnections;
            System.out.println("Average Wait Time: " + avgWaitTime + "ms");
            System.out.println("Average IO Time: " + avgIoTime + "ms");
            return avgWaitTime/avgIoTime;
        } else {
            System.out.println("No connections yet.");
            return 0;
        }
    }
}
